<template>
<div class="common-wrapper">
  <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
    <a-form-model-item label="考勤表格类型" prop="originalFormatType">
      <a-radio-group v-model="form.originalFormatType">
        <a-radio value="0"> 打卡明细 </a-radio>
        <a-radio value="1"> 考勤明细 </a-radio>
      </a-radio-group>
    </a-form-model-item>

    <a-form-model-item label="上传表格">
      <a-upload :file-list="form.excel" @remove="form.excel = []" :before-upload="beforeUpload">
        <a-button> <a-icon type="upload" /> 选择文件 </a-button>
      </a-upload>
    </a-form-model-item>

    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="uploading" style="margin-top: 16px" @click="onSubmit">
        {{ uploading ? '转换中' : '开始转换' }}
      </a-button>
    </a-form-model-item>
  </a-form-model>
</div>
</template>

<script>
import { apiConvert } from '@/api/attendance'
export default {
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      uploading: false,

      form: {
        originalFormatType: '0',
        excel: [],
      },
      rules: {
        originalFormatType: [{ required: true, message: '请选择考勤表格类型', trigger: 'change' }],
      }
    }
  },
  methods: {
    onSubmit() {
      this.uploading = true
      const formData = new FormData()
      formData.append('excel', this.form.excel[0])
      formData.append('original_format_type', this.form.originalFormatType)

      apiConvert('convert', formData)
        .then((response) => {
          if (!response) {
            return
          }
          const blob = new Blob([response])
          const fileName = `电子考勤.xlsx`;
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            const link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            URL.revokeObjectURL(link.href)
          }
        })
        .finally(() => {
          this.uploading = false
        })
    },
    beforeUpload(file) {
      if (
        file.type !== 'application/vnd.ms-excel' &&
        file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ) {
        this.$message.error('文件格式错误，只能选择.xls或.xlsx文件')
        return false
      }
      this.form.excel = [file]
      return false
    },
  },
}
</script>
